//
//  WJQNearbyViewController.m
//  TripTogether
//
//  Created by dllo on 15/12/23.
//  Copyright © 2015年 王军岐. All rights reserved.
//

#import "WJQNearbyViewController.h"
#import "WJQNearbyModel.h"
#import "WJQNearbyCollectionViewCell.h"


@interface WJQNearbyViewController () <UICollectionViewDataSource, UICollectionViewDelegate, WJQNearbyCollectionViewDelegate>


@property (nonatomic, retain) UIScrollView *scrollView;

@property (nonatomic, retain) NSMutableArray *btnArray;

@property (nonatomic, retain) UIButton *beforeButton;

@property (nonatomic, retain) UIView *selectView;

@property (nonatomic, retain) UICollectionView *collectionView;

@property (nonatomic, retain) NSMutableDictionary *otherDic;

@property (nonatomic, retain) NSMutableArray *keyArray;

@property (nonatomic, retain) NSMutableArray *isLoad;

@property (nonatomic, retain) UIColor *textColor;

@property (nonatomic, assign) CGPoint location;

@property (nonatomic, assign) BOOL isLocation;

@property (nonatomic, retain) MBProgressHUD *mbBarPrpgressV;

@end

@implementation WJQNearbyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor colorWithRed:0.98 green:0.96 blue:0.91 alpha:1];
    
    //navigation
    self.navigationItem.title = @"附近";
    
    //地点类型
    self.otherDic = [NSMutableDictionary dictionary];
    //判断是否加载
    self.isLoad = [NSMutableArray array];
    //地点类型
    self.keyArray = [NSMutableArray arrayWithObjects:@"0", @"11", @"10", @"5", @"21", @"6", nil];
    for (NSString *temp in self.keyArray) {
        [self.isLoad addObject:@"0"];
        [self.otherDic setObject:[NSMutableArray array] forKey:temp];
    }
    
    NSLog(@"%ld", self.initNum);

    //返回按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_nav_back_button"] style:UIBarButtonItemStylePlain target:self action:@selector(leftAction:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    [self createScrollView];
    
    //collectionView
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT - 94);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    flowLayout.minimumLineSpacing = 0;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 30, SCREEN_WIDTH, SCREEN_HEIGHT - 94) collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor clearColor];
    self.collectionView.pagingEnabled = YES;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerClass:[WJQNearbyCollectionViewCell class] forCellWithReuseIdentifier:@"otherItem"];
    [self.view addSubview:self.collectionView];

    
    NSIndexPath *index = [NSIndexPath indexPathForRow:self.initNum inSection:0];
    [self.collectionView scrollToItemAtIndexPath:index atScrollPosition:UICollectionViewScrollPositionRight animated:YES];
    


    [self setSelectNum:self.initNum];
    
}
- (void)createScrollView {
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
    self.scrollView.contentSize = CGSizeMake(SCREEN_WIDTH * 1.2, 40);
    self.scrollView.scrollEnabled = NO;
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"states"] isEqualToString:@"1"]) {
        self.scrollView.backgroundColor = [UIColor blackColor];
        self.textColor = [UIColor whiteColor];
    }
    else {
        
        self.scrollView.backgroundColor = [UIColor whiteColor];
        self.textColor = [UIColor whiteColor];
    }
    [self.view addSubview:self.scrollView];

    
    self.btnArray = [NSMutableArray array];
    

    
    // CGRectMake(SCREEN_WIDTH / 5, 30 - 3, SCREEN_WIDTH / 5, 3)
    self.selectView = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH / 5, 5, SCREEN_WIDTH / 5 - 10, 30 - 5 * 2)];
    //    self.selectView.backgroundColor = [UIColor colorWithRed:0.156 green:0.803 blue:0.607 alpha:1.000];
    
    self.selectView.backgroundColor = [UIColor colorWithRed:0.32 green:0.74 blue:0.8 alpha:1];
    self.selectView.layer.cornerRadius = 10.f;
    [self.scrollView addSubview:self.selectView];
    
    NSArray *array = [NSArray arrayWithObjects:@"全部", @"景点", @"住宿", @"餐饮", @"娱乐", @"购物", nil];
    
    for (int i = 0; i < 6; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(SCREEN_WIDTH / 5 * i, 0, SCREEN_WIDTH / 5, 30);
        button.titleLabel.font = [UIFont systemFontOfSize:14];
        [button setTitle:array[i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        button.tag = 1000 + i;
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.scrollView addSubview:button];
        [self.btnArray addObject:button];
    }
    

    
}
#pragma mark - 导航按钮点击事件
- (void)buttonAction:(UIButton *)button {
    
    if (![button isEqual:self.beforeButton]) {
        
        //判断当前的区是否请求过网络
        if ([[self.isLoad objectAtIndex:button.tag - 1000] isEqualToString:@"0"]) {
            
            [self AFNWorkingWithCategory:[self.keyArray objectAtIndex:button.tag - 1000]];
            [self.isLoad replaceObjectAtIndex:button.tag - 1000 withObject:@"1"];
        }
        //设置scrollView 的偏移量
        if (button.tag == 1004 && self.scrollView.contentOffset.x == 0) {
            [self.scrollView setContentOffset:CGPointMake(SCREEN_WIDTH / 5, 0) animated:YES];
        }
        if (button.tag == 1001 && self.scrollView.contentOffset.x == SCREEN_WIDTH / 5) {
            [self.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
        }
        //设置button大小和滑块位置
        NSIndexPath *index = [NSIndexPath indexPathForRow:button.tag - 1000 inSection:0];
        [self.collectionView scrollToItemAtIndexPath:index atScrollPosition:UICollectionViewScrollPositionRight animated:YES];
        
        [self.beforeButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        CGRect frame = self.selectView.frame;
        frame.origin.x = button.frame.origin.x + 5;
        
        [UIView animateWithDuration:0.2 animations:^{
            
            self.selectView.frame = frame;
            self.beforeButton.transform = CGAffineTransformMakeScale(1, 1);
            button.transform = CGAffineTransformMakeScale(1.05, 1.05);
        }];
        [button setTitleColor:self.textColor forState:UIControlStateNormal];
        self.beforeButton = button;
        
    }
}
#pragma mark 设置导航
- (void)setSelectNum:(NSInteger)selectNum {
    
    //判断当前的区是否请求过数据
    if ([[self.isLoad objectAtIndex:selectNum] isEqualToString:@"0"]) {
        
        [self AFNWorkingWithCategory:[self.keyArray objectAtIndex:selectNum]];
        [self.isLoad replaceObjectAtIndex:selectNum withObject:@"1"];
    }
    
    UIButton *button = [self.btnArray objectAtIndex:selectNum];
    
    if (![button isEqual:self.beforeButton]) {
        
        if (button.tag >= 1004 && self.scrollView.contentOffset.x == 0) {
            [self.scrollView setContentOffset:CGPointMake(SCREEN_WIDTH / 5, 0) animated:YES];
        }
        if (button.tag <= 1001 && self.scrollView.contentOffset.x == SCREEN_WIDTH / 5) {
            [self.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
        }
        
        [self.beforeButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        CGRect frame = self.selectView.frame;
        frame.origin.x = button.frame.origin.x + 5;
        
        [UIView animateWithDuration:0.2 animations:^{
            
            self.selectView.frame = frame;
            self.beforeButton.transform = CGAffineTransformMakeScale(1, 1);
            button.transform = CGAffineTransformMakeScale(1.05, 1.05);
            
            
        }];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

            [button setTitleColor:self.textColor forState:UIControlStateNormal];
            
        });

        self.beforeButton = button;
    }
    
}

#pragma mark - collectionView
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return 6;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    
    WJQNearbyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"otherItem" forIndexPath:indexPath];
    cell.otherArray = [self.otherDic objectForKey:self.keyArray[indexPath.row]];
    cell.contentView.backgroundColor = [UIColor clearColor];
    cell.delegate = self;
    
    return cell;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    NSInteger index = scrollView.contentOffset.x / SCREEN_WIDTH;
    [self setSelectNum:index];
}

#pragma mark - 代理方法
- (void)pushDetailViewController:(NSString *)Id {
    
    NSLog(@"----%@", Id);
//    WSOtherDetailViewController *otherDVC = [[WSOtherDetailViewController alloc] init];
//    otherDVC.Id = Id;
//    [self.navigationController pushViewController:otherDVC animated:YES];

}

#pragma mark - 返回
- (void)leftAction:(UIBarButtonItem *)bar {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - AFN网络请求
- (void)AFNWorkingWithCategory:(NSString *)category {
    
//    self.mbBarPrpgressV = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    [self.mbBarPrpgressV show:YES];

    // 显示菊花
    [self MBShow];
    
    NSString *strUrl = [NSString stringWithFormat:@"http://api.breadtrip.com/place/pois/nearby/?keyword=&category=%@&start=0&count=20&latitude=%f&longitude=%f", category, 39.02f, 121.45f];
    
//    NSLog(@"%@", strUrl);
    
    
    [WJQNetwork getAFNet:strUrl block:^(id result) {
        
        NSDictionary *bigDic = result;

        NSMutableArray *otherArray = [self.otherDic objectForKey:category];
        
        for (NSDictionary *dic in [bigDic objectForKey:@"items"]) {
            WJQNearbyModel *other = [WJQNearbyModel modelWithDicationary:dic];
            [otherArray addObject:other];
        }
        

        
        [self.collectionView reloadData];

//        [self.mbBarPrpgressV hide:YES];
        
        // 隐藏菊花
        [self MBHide];
    } errorBlock:^(NSError *error) {
        
        [self NetworkError:^{
            
            [self dismissViewControllerAnimated:YES completion:nil];
        }];
    }];
}
- (void)viewWillAppear:(BOOL)animated {
    
    self.navigationController.navigationBar.translucent = NO;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
